<template>
  <a-menu
    v-model:openKeys="openKeys"
    v-model:selectedKeys="selectedKeys"
    mode="inline"
    :collapsed="collapsed"
    :inline-indent="0"
    style="padding-top: 24px"
    @click="toJump"
  >
    <template v-for="item in menuList" :key="item.key">
      <a-sub-menu v-if="item.children" :key="item.key">
        <template #title>
          <span style="padding-left: 30px">{{ item.label }}</span>
        </template>
        <a-menu-item v-for="child in item.children" :key="child.key">
          <span style="padding-left: 30px">{{ child.label }}</span>
        </a-menu-item>
      </a-sub-menu>
      <a-menu-item v-if="!item.children" :key="item.key">
        <template v-if="item.key === '/list'" #icon>
          <HomeOutlined style="padding-left: 30px" />
        </template>
        <span>{{ item.label }}</span>
      </a-menu-item>
    </template>
  </a-menu>
</template>

<script lang="ts">
  import { defineComponent, ref, PropType, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { BaseArray } from '@/types/global';
  import { menuList } from './config';

  export default defineComponent({
    props: {
      collapsed: {
        type: Boolean as PropType<Boolean>,
        default: false,
      },
    },
    setup() {
      const router = useRouter();
      const route = useRoute();
      const selectedKeys: BaseArray = ref([]);
      const openKeys: BaseArray = ref([]);

      function active() {
        const hash = window.location.hash.replace('#', '');
        selectedKeys.value = [];
        menuList.value.forEach((p) => {
          if (p.children) {
            p.children.forEach((c) => {
              if ((c.includePaths as BaseArray).includes(hash)) {
                openKeys.value = [...openKeys.value, p.key, c.key];
                selectedKeys.value = [c.key];
              }
            });
          } else if ((p.includePaths as BaseArray).includes(hash)) {
            selectedKeys.value = [p.key];
          }
        });
      }
      function toJump({ key }) {
        router.push(key);
      }
      watch(menuList, active);
      watch(route, active);
      return {
        openKeys,
        selectedKeys,
        menuList,
        toJump,
      };
    },
  });
</script>

<style lang="less" scoped></style>
